<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { usetikuUserStore } from '@/stores/sj-user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = usetikuUserStore()

const resetForm = reactive({
  account: '',
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})

const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
const formRef = ref(null)

const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 发送验证码
const sendVerificationCode = async () => {
  try {
    await formRef.value.validateField(['account', 'email'])
    sendingCode.value = true
    
    try {
      await userStore.sendVerificationCode(resetForm.account, resetForm.email)
      ElMessage.success('验证码已发送到您的邮箱')
      
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
          sendingCode.value = false
        }
      }, 1000)
    } catch (error) {
      // 根据后端返回的错误类型显示相应的错误提示
      let errorMessage = error.message || '验证码发送失败';
      // 根据错误码显示特定提示
      switch (error.code) {
        case 1001: // ACCOUNT_NOT_EXIST
          errorMessage = '账号不存在，请检查您的账号'
          break
        case 1010: // EMAIL_ERROR
          errorMessage = '邮箱与账号不匹配，请检查您的邮箱'
          break
        case 1005: // VERIFICATION_CODE_ERROR
          errorMessage = '验证码错误或已过期，请重新获取'
          break
      }
      
      ElMessage.error(errorMessage)
      sendingCode.value = false
    }
  } catch (error) {
    // 表单验证失败
  }
}

// 重置密码
const handleResetPassword = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.resetPassword(
          resetForm.account,
          resetForm.email,
          resetForm.verificationCode,
          resetForm.newPassword
        )
        ElMessage.success('密码重置成功，请使用新密码登录')
        router.push('/login')
      } catch (error) {
        console.error('密码重置失败:', error)
        
        // 直接使用error对象中的message和code
        let errorMessage = error.message || '密码重置失败，请检查输入信息'
        
        // 根据错误码显示特定提示
        switch (error.code) {
          case 1001: // ACCOUNT_NOT_EXIST
            errorMessage = '账号不存在，请检查您的账号'
            break
          case 1010: // EMAIL_ERROR
            errorMessage = '邮箱与账号不匹配，请检查您的邮箱'
            break
          case 1005: // VERIFICATION_CODE_ERROR
            errorMessage = '验证码错误或已过期，请重新获取'
            break
        }
        
        ElMessage.error(errorMessage)
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="forget-password-container">
    <div class="forget-password-box">
      <div class="forget-password-header">
        <h2>重置密码</h2>
        <p>请填写以下信息重置您的密码</p>
      </div>
      
      <el-form
        ref="formRef"
        :model="resetForm"
        :rules="rules"
        label-position="top"
        class="reset-form"
      >
        <el-form-item label="账号" prop="account">
          <el-input 
            v-model="resetForm.account" 
            placeholder="请输入您的账号"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="resetForm.email" 
            placeholder="请输入注册时使用的邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-code-row">
            <el-input 
              v-model="resetForm.verificationCode" 
              placeholder="请输入验证码"
              class="verification-input"
            />
            <el-button 
              type="primary" 
              :disabled="sendingCode || countdown > 0" 
              @click="sendVerificationCode"
              class="send-code-button"
            >
              {{ countdown > 0 ? `${countdown}秒后重新发送` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="resetForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            prefix-icon="Lock"
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="resetForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            prefix-icon="Lock"
          />
        </el-form-item>
        
        <div class="form-actions">
          <el-button 
            type="primary" 
            :loading="loading" 
            @click="handleResetPassword"
            class="reset-button"
          >
            重置密码
          </el-button>
          
          <div class="back-to-login">
            <a @click="goToLogin">返回登录</a>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.forget-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.forget-password-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.forget-password-header {
  text-align: center;
  margin-bottom: 30px;
}

.forget-password-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.forget-password-header p {
  font-size: 14px;
  color: #909399;
}

.reset-form {
  margin-top: 20px;
}

.verification-code-row {
  display: flex;
  gap: 10px;
}

.verification-input {
  flex: 1;
}

.send-code-button {
  width: 140px;
}

.form-actions {
  margin-top: 30px;
}

.reset-button {
  width: 100%;
  padding: 12px 0;
}

.back-to-login {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
}

.back-to-login a {
  color: #409eff;
  cursor: pointer;
}
</style>